package data;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import fileProcessing.ParsingException;
import fileProcessing.ProjectDirectories;

public class StringType extends AbstractDataType<StringType>{

	private String value;
	private String fieldType = "String(general field)";
	private String filename = ProjectDirectories.dataFileDir+"\\UTF_Collection";
	private RandomAccessFile dataFile;
	
	public StringType(RandomAccessFile raf) throws ParsingException{
		try {
			dataFile = new RandomAccessFile(filename,"r");
			dataFile.seek(raf.readLong());
			value = dataFile.readUTF();
			dataFile.close();
		} catch (IOException e) {
			throw new ParsingException("Error reading string value from UTF_Collection file.");
		}
	}
	
	public StringType(String input){
		value = input;
		String [] enclosures = {"'","\""};
		Pattern ChkEnclosure;
		Matcher match;
		
		ChkEnclosure = Pattern.compile("\"(.*)\"", Pattern.CASE_INSENSITIVE);
		match = ChkEnclosure.matcher(input);
		if(match.find()){
			value = match.group(1);
		}
		else{
			ChkEnclosure = Pattern.compile("'(.*)'", Pattern.CASE_INSENSITIVE);
			match = ChkEnclosure.matcher(input);
			if(match.find()){
				value = match.group(1);
			}
			else
				value = input;
		}
	}
	
	@Override
	public String toString() {
		return value;
	}
	
	public void writeValue(RandomAccessFile raf) throws ParsingException{
		try {
			dataFile = new RandomAccessFile(filename,"rw");
			dataFile.seek(dataFile.length());
			raf.writeLong(dataFile.getFilePointer());
			dataFile.writeUTF(value);
			dataFile.close();
		} catch (IOException e) {
			throw new ParsingException("Error writing value "+value+" to data file.");
		}
	}

	@Override
	public int compareTo(StringType o) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public boolean isValid(String s) {
		return true;
	}

	@Override
	public String getType() {
		return fieldType;
	}

}
